<?php

class TemplateGenerator
{

  function isValidZip($file,$name)
  {
    $error = 0;
    $zip = new ZipArchive();
    if ($zip->open($file) === TRUE)
    {
      for ($i=0; $i < $zip->numFiles; $i++)
      {
        $fileinfo = $zip->statIndex($i);
        $fileinfo_array = explode("/",$fileinfo['name']);
        if (count($fileinfo_array) != 2)
        {
          $error++;
        }
        if ($fileinfo_array[0] != basename($name,".zip"))
        {
          $error++;
        }
      }
      $zip->close();
    }
    else
    {
      $error++;
    }
    return ($error == 0);
  }
  
  
  function createTemplate($file,$name, $user_template_dir)
  {
    $error = 0;
    $template_dir = $user_template_dir;   //dirname(__FILE__)."/../templates/";
    $destination_dir = $template_dir.basename($name,".zip");

    if (file_exists($destination_dir))
    {
      //TODO: error handling
      return;
    }

    if ($this->isValidZip($file, $name))
    {
      $zip = new ZipArchive();
      $zip->open($file);
      $zip->extractTo($template_dir);
      // Good idea? (needed for testing)
      chmod($destination_dir, 0777);
      $zip->close();
    }
    // TODO: Error handling
  }

}
?>